package controller;

import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.swing.JOptionPane;
import javax.swing.*;
import po.Room;
import po.Student;
import service.ContactsService;
import view.StudentDialog;
import view.ContactsFrame;
import view.OverviewDialog;
import view.RoomDialog;

/**
 * @author 27261
 *MVC模式的controller类
 *通讯录信息管理类
 */
public class ContactsControllerListener implements ActionListener{
	private ContactsFrame contactsFrame;
	private StudentDialog studentDialog;
	private RoomDialog roomDialog;
	private ContactsService contactsService;
	private OverviewDialog overviewDialog;
	public ContactsControllerListener() {
		this.contactsService = new ContactsService();
	}
	
	/**
	 *对一切事件的处理 尽量能在一个类里边实现
	 *
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		//打开新增对话框
		if("addDialog".equals(e.getActionCommand())) { 
			
			studentDialog = new StudentDialog(contactsFrame,"添加学生信息",null);	
		}
		
		//新增提交
		else if("studentAddPost".equals(e.getActionCommand())) { 
			Student student = new Student();
			student = this.getStudentInstance();
			if(student != null) {
				contactsService.addStudent(student);
				JOptionPane.showMessageDialog(contactsFrame, "通讯录中已添加"+student.getName()+"的信息！");
				studentDialog.dispose();
				contactsFrame.studentRefresh(contactsService.findAllStudent());
			}else {
				JOptionPane.showMessageDialog(contactsFrame, "添加失败！");
			}
			
		}
		
		//打开查询对话框
		else if("searchDialog".equals(e.getActionCommand())) { 
			String str = JOptionPane.showInputDialog(overviewDialog, "输入联系人的姓名");
			if(str != null && !"".equals(str)) { //str不为null且str内容不为""
					List<Student> list = null;
					String name = str;
					list = contactsService.searchStudentByName(name);
					if(!list.isEmpty())
						contactsFrame.showStudentSearchSuccessResult(list);
					else
						contactsFrame.showStudentSearchFalseResult(list);
			}
		}
		
		//打开修改联系人对话框
		else if("updateDialog".equals(e.getActionCommand())) { 
			int selRow = overviewDialog.getSelRow();
			if(selRow<0) {
				JOptionPane.showMessageDialog(overviewDialog, "请选择一行数据");
			}else {
				Student student = null;
				if(contactsService.findAllStudent().get(overviewDialog.getSelRow())!=null)
					student = contactsService.findAllStudent().get(overviewDialog.getSelRow());
				studentDialog = new StudentDialog(overviewDialog,"修改联系人信息",student);
			}
		}
		 //修改提交
		else if("updatePost".equals(e.getActionCommand())) { //修改提交
			Student updatedStudent = this.getStudentInstance();
			if(updatedStudent != null) {
				contactsService.updateStudent(contactsFrame.getStudentId(), updatedStudent);
				JOptionPane.showMessageDialog(contactsFrame, "信息修改成功！");
				studentDialog.dispose();
				contactsFrame.studentRefresh(contactsService.findAllStudent());
				overviewDialog.studentRefresh(contactsService.findAllStudent());
			}else {
				JOptionPane.showMessageDialog(contactsFrame, "更新学生失败！");
			}	
		}
		 //删除学生操作
		else if("delete".equals(e.getActionCommand())) {
			Long studentId = overviewDialog.getStudentId();
			Student student = contactsService.getStudent(studentId);
			contactsService.deleteStudent(studentId);
			JOptionPane.showMessageDialog(overviewDialog, "删除"+student.getName()+"信息成功！");
			contactsFrame.studentRefresh(contactsService.findAllStudent());
			overviewDialog.studentRefresh(contactsService.findAllStudent());
		}
		//打开新增对话框
		else if("addRoomDialog".equals(e.getActionCommand())) { 
			roomDialog = new RoomDialog(contactsFrame,"添加宿舍信息",null);	
		}
		//新增提交
		else if("roomAddPost".equals(e.getActionCommand())) { 
			Room room = new Room();
			room = this.getRoomInstance();
			if(room != null) {
				contactsService.addRoom(room);
				JOptionPane.showMessageDialog(contactsFrame, "宿舍表中已添加"+room.getRoom_name()+"的信息！");
				roomDialog.dispose();
				contactsFrame.roomRefresh(contactsService.findAllRoom());
			}else {
				JOptionPane.showMessageDialog(contactsFrame, "添加失败！");
			}
			
		}
		//打开修改宿舍对话框
		else if("updateRoomDialog".equals(e.getActionCommand())) { 
			int selRow = overviewDialog.getSelRow();
			if(selRow<0) {
				JOptionPane.showMessageDialog(overviewDialog, "请选择一行数据");
			}else {
				Room room = null;
				if(contactsService.findAllRoom().get(overviewDialog.getSelRow())!=null)
					room = contactsService.findAllRoom().get(overviewDialog.getSelRow());
				roomDialog = new RoomDialog(overviewDialog,"修改宿舍信息",room);
			}
		}
		 //修改提交
		else if("updateRoomPost".equals(e.getActionCommand())) { //修改提交
			Room updatedRoom = this.getRoomInstance();
			if(updatedRoom != null) {
				contactsService.updateRoom(contactsFrame.getRoomId(), updatedRoom);
				JOptionPane.showMessageDialog(contactsFrame, "信息修改成功！");
				roomDialog.dispose();
				contactsFrame.roomRefresh(contactsService.findAllRoom());
				overviewDialog.roomRefresh(contactsService.findAllRoom());
			}else {
				JOptionPane.showMessageDialog(contactsFrame, "更新失败！");
			}	
		}
		 //删除宿舍操作
		else if("deleteRoom".equals(e.getActionCommand())) {
			int roomId = overviewDialog.getRoomId();
			Room room = contactsService.getRoom(roomId);
			contactsService.deleteRoom(roomId);
			JOptionPane.showMessageDialog(overviewDialog, "删除"+room.getRoom_name()+"信息成功！");
			contactsFrame.roomRefresh(contactsService.findAllRoom());
			overviewDialog.roomRefresh(contactsService.findAllRoom());
		}
		//总览学生、宿舍操作
		else if("overviewStudent".equals(e.getActionCommand())) {
			this.overviewDialog = new OverviewDialog(contactsFrame,"通讯录");
		}
		else if("overviewRoom".equals(e.getActionCommand())) {
			this.overviewDialog = new OverviewDialog(contactsFrame,"宿舍列表");
		}
		//复制联系人或者宿舍操作
		else if("copyStudent".equals(e.getActionCommand())) { 
			int selRow = overviewDialog.getSelRow();
			if(selRow<0) {
				JOptionPane.showMessageDialog(overviewDialog, "请选择一行数据");
			}else {
				Student student = null;
				if(contactsService.findAllStudent().get(overviewDialog.getSelRow())!=null)
					student = contactsService.findAllStudent().get(overviewDialog.getSelRow());
		        StringSelection stsel = new StringSelection(student.toString());
		        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
		        JOptionPane.showMessageDialog(overviewDialog, "复制"+student.getName()+"信息成功！");
			}
		}
		else if("copyRoom".equals(e.getActionCommand())) { 
			int selRow = overviewDialog.getSelRow();
			if(selRow<0) {
				JOptionPane.showMessageDialog(overviewDialog, "请选择一行数据");
			}else {
				Room room = null;
				if(contactsService.findAllRoom().get(overviewDialog.getSelRow())!=null)
					room = contactsService.findAllRoom().get(overviewDialog.getSelRow());
		        StringSelection stsel = new StringSelection(room.toString());
		        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
		        JOptionPane.showMessageDialog(overviewDialog, "复制"+room.getRoom_name()+"信息成功！");
			}
		}
	}
	/**
	 * 获取学生vo实例
	 * Student为dialog传递的vo对象
	 * @return Student
	 */
	public Student getStudentInstance() {
		SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd");
		String name = null;
		long studentId = 0;
		Date birthday = null;
		String phoneNumber = null;
		String email = null;
		String native_place = null;
		String address = null;
		String roomName = null;
		Room room = new Room();
		Student student = null;
		/*获取学号*/
		String studentIDInput  = studentDialog.getStudentIdTextField().getText().trim();
		if(studentIDInput != null && !"".equals(studentIDInput)) {
			if(studentIDInput.matches("^[0-9]*$"))/*判断字符是否与指定的 正则表达式 相匹配*/{
				studentId = Long.parseLong(studentIDInput);
			}
			else {
				JOptionPane.showMessageDialog(contactsFrame, "学号必须是整数类型","输入错误",JOptionPane.ERROR_MESSAGE);
			}
		}else {
			JOptionPane.showMessageDialog(contactsFrame, "学号不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
		}
		/*获取姓名*/
		String nameInput = studentDialog.getNameTextField().getText().trim();
		if(nameInput != null && !"".equals(nameInput)/*当nameInput的值不为空时*/) {
			name = nameInput;
		}else {
			JOptionPane.showMessageDialog(contactsFrame, "名称不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
		}
		/*获取生日*/
		String birthdayInput = studentDialog.getDateTextField().getText().trim();
		if(birthdayInput != null && !"".equals(birthdayInput) && birthdayInput.equals("例如：2000-01-01")) {
			if(birthdayInput.equals("例如：2000-01-01")){
				JOptionPane.showMessageDialog(contactsFrame, "生日不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
			}
			else if(birthdayInput.matches("[0-9-]+")) {
				try {
					birthday = simple.parse(birthdayInput);
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			else {
				JOptionPane.showMessageDialog(contactsFrame, "生日输入格式有误","输入错误",JOptionPane.ERROR_MESSAGE);
			}
		}
		
		/*获取宿舍*/
		String roomNameInput = studentDialog.getRoomNameTextField().getText().trim();
		if(roomNameInput != null && !"".equals(roomNameInput) && roomNameInput.equals("例如：泰山区1-111")) {
			if(roomNameInput.equals("例如：泰山区1-111")) {
				JOptionPane.showMessageDialog(contactsFrame, "宿舍不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
			}
			else{
				roomName = roomNameInput;
				room.setRoom_name(roomName);
			}
		}
		/*获取住址*/
		String addressInput = studentDialog.getAddressTextField().getText().trim();
		if(addressInput != null && !"".equals(addressInput)/*当addressInput的值不为空时*/&& addressInput.equals("例如：广东汕头")) {
			if(addressInput.equals("例如：广东汕头")) {
				JOptionPane.showMessageDialog(contactsFrame, "宿舍不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
			}
			else
				address = addressInput;
		}
		/*获取出生地*/
		String nativePlaceInput = studentDialog.getNativePlaceTextField().getText().trim();
		if(nativePlaceInput != null && !"".equals(nativePlaceInput)/*当addressInput的值不为空时*/&& nativePlaceInput.equals("例如：广东汕头")) {
			if(nativePlaceInput.equals("例如：广东汕头")) {
				JOptionPane.showMessageDialog(contactsFrame, "住址不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
			}
			else
				native_place = nativePlaceInput;
		}
		/*获取手机号码*/
		String phoneNumInput  = studentDialog.getPhoneNumTextField().getText().trim();
		if(phoneNumInput != null && !"".equals(phoneNumInput)/*当phoneNumInput的值不为空时*/) {
			phoneNumber = phoneNumInput;
		}else {
			JOptionPane.showMessageDialog(contactsFrame, "手机号码不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
		}
		/*获取邮箱地址*/
		String emailInput  = studentDialog.getEmailTextField().getText().trim();
		if(emailInput != null && !"".equals(emailInput)/*当emailInput的值不为空时*/) {
			email = emailInput;
		}else {
			JOptionPane.showMessageDialog(contactsFrame, "邮箱不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
		}
		if(studentId > 0 && roomName!=null && name!=null && birthday != null && address != null && native_place != null && phoneNumber != null && email != null) {
			student = new Student(name, studentId, birthday, phoneNumber, email, native_place, address, room);
		}
		return student;
	}
	/**
	 * 获取宿舍vo实例
	 * room为dialog传递的vo对象
	 * @return room
	 */
	public Room getRoomInstance() {
		String name = null;
		int roomId = 0;
		Room room = new Room();
		/*获取宿舍号*/
		String roomIDInput  = roomDialog.getIdTextField().getText().trim();
		if(roomIDInput != null && !"".equals(roomIDInput)) {
			if(roomIDInput.matches("^[0-9]*$"))/*判断字符是否与指定的 正则表达式 相匹配*/{
				roomId = Integer.parseInt(roomIDInput);
			}
			else {
				JOptionPane.showMessageDialog(contactsFrame, "宿舍号必须是整数类型","输入错误",JOptionPane.ERROR_MESSAGE);
			}
		}else {
			JOptionPane.showMessageDialog(contactsFrame, "宿舍号不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
		}
		/*获取宿舍名*/
		String nameInput = roomDialog.getNameTextField().getText().trim();
		if(nameInput != null && !"".equals(nameInput)/*当nameInput的值不为空时*/) {
			name = nameInput;
		}else {
			JOptionPane.showMessageDialog(contactsFrame, "名称不能为空","输入错误",JOptionPane.ERROR_MESSAGE);
		}
		if(roomId > 0 && name!=null) {
			room = new Room(roomId, name);
		}
		return room;
	}
	public void setContactsFrame(ContactsFrame contactsFrame) {
		this.contactsFrame = contactsFrame;
	}
	public ContactsService getContactsService() {
		return contactsService;
	}
	public void setStudentAddDialog(StudentDialog studentAddDialog) {
		this.studentDialog = studentAddDialog;
	}
	public void setRoomAddDialog(RoomDialog roomAddDialog) {
		this.roomDialog = roomAddDialog;
	}
	public void setOverViewDialog(OverviewDialog overviewDialog) {
		this.overviewDialog = overviewDialog;
	}
	public OverviewDialog setOverViewDialog() {
		return this.overviewDialog;
	}
}


